package com.davinci.freemarket.businessLayer.servlets;

import java.io.IOException;
import java.util.Date;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.davinci.freemarket.dataModelLayer.model.UserModel;

/**
 * Servlet implementation class AccessControlFilter
 * 
 * @author Lucas Buyo
 */
public class AccessControlFilter implements Filter 
{
	private static final long serialVersionUID = 1L;
	
	/**
	 * Define si el usuario tiene acceso o no al sistema
	 */
	protected Boolean authorized = false;
	
	/**
	 * 
	 */
	protected FilterConfig filterConfig;

	/**
	 * 
	 */
	protected String loginPage;

	/**
	 * 
	 */
	private String mainPage;
	
	
       
    /*************************************
     * @see HttpServlet#HttpServlet()
     *************************************/
    public AccessControlFilter() {
        super();
    }

	@Override
	public void destroy() {
		
	}
	

	@Override
	public void init(FilterConfig config) throws ServletException 
	{
		filterConfig = config;
		
        //Get init parameter
        loginPage = config.getInitParameter("login_page");
 
        //Get init parameter
        mainPage = config.getInitParameter("main_page");
        
        //Print the init parameter
        System.out.println("LoginPage init param: " + loginPage);
	}
	

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException 
	{
//		chain.doFilter(request, response);
		
		//-- obtngo el servlet que envia este request
	    if (request instanceof HttpServletRequest) {
			//-- obtengo la session actual
	        HttpSession session = ((HttpServletRequest)request).getSession(false);
	        if (session != null) {
	    		//-- valido que el usuario tenga session activa en el sistema
	    		UserModel usermodel = (UserModel)session.getAttribute("currentSessionUser");
	            if (usermodel != null)
	                authorized = true;
	        }
	    }
	    
	    if (authorized) {
	        chain.doFilter(request, response);
	        return;
	    } else if (filterConfig != null) {
//	    	 filterConfig.getServletContext().getContextPath();
	    	 String login_page = filterConfig.getInitParameter("login_page");
	        if (login_page != null && !"".equals(login_page)) {
//	            filterConfig.getServletContext().getRequestDispatcher(login_page).forward(request, response);
		        chain.doFilter(request, response);
	            return;
	        }
	    }		 
	    
	    throw new ServletException("Unauthorized access, unable to forward to login page");
	    
	}


}
